package com.lxl.securitypermission.config.custom;

import com.lxl.securitypermission.entity.SUser;
import com.lxl.securitypermission.pojo.SecUser;
import com.lxl.securitypermission.service.RoleService;
import com.lxl.securitypermission.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author 绫小路
 * @date 2020/12/29 22:39
 * @description
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

  @Autowired
  private UserService userService;
  @Autowired
  private RoleService roleService;

  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    SUser user = userService.get(s);
    if (user == null) {
      throw new UsernameNotFoundException("用户不存在！");
    }
    if (user.getStatus() == 0) {
      throw new RuntimeException("账号被冻结，无法登录");
    }
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    List<String> roles = roleService.getRoleList(user.getId());
    roles.forEach(r -> {
      //security的验证规则需要 ROLE_需要存在 ROLE_
      grantedAuthorities.add(new SimpleGrantedAuthority(r));
    });
    //账号密码，密码为明文
    String password = new BCryptPasswordEncoder().encode(user.getPassword());
    //转化为密码，security验证需要密文
    SecUser secUser = new SecUser(s, password, grantedAuthorities);
    secUser.setUsername(s);
    secUser.setNickname(user.getNickname());
    secUser.setId(user.getId());
    return secUser;
  }
}
